package com.du; /**
 * @author : DuJiabao
 * @Date : 2021/1/31 18:52
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc : 接受用户上传过来的文件
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReceiveServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("接收到了数据");
    //POST解决中文乱码问题
    request.setCharacterEncoding("UTF-8");
    // 检查request的contentType 是不是 multipart/ 开头的
    if (ServletFileUpload.isMultipartContent(request)) {
      FileItemFactory fileItemFactory = new DiskFileItemFactory();
      // 创建用于解析上传文件的工具类
      ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
      try {
        // 取出传入的所有数据，以List的方式存储
        List<FileItem> list = servletFileUpload.parseRequest(request);
        for (FileItem fileItem : list) {
          // 如果只是普通的属性数据
          if (fileItem.isFormField()) {
            System.out.println(fileItem.getFieldName());
            System.out.println(fileItem.getString("UTF-8"));
          } else {
            //如果是文件
            System.out.println(fileItem.getFieldName());
            System.out.println(fileItem.getName());
            //将文件写入指定目录
            fileItem.write(new File("E:/" + fileItem.getName()));
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}














